package ua.cs.stu.ics.xml;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import ua.cs.stu.ics.label.JLabelExtended;
import ua.cs.stu.ics.utils.Util;


import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 26.02.11
 * Time: 20:38
 * To change this template use File | Settings | File Templates.
 */
public class Dom4jWriter {
    private Document createDocument(JPanel jPanel, boolean writeAllText) {
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");


        ArrayList<Component> compList = Util.getAllComponents(jPanel);


        for (Component component : compList) {
            if (component instanceof JLabelExtended) {
                if (((JLabelExtended) component).getName() == null)
                    continue;
                if (!((JLabelExtended) component).isFromDatabase() || writeAllText) {
                    Element item = root.addText("\n")
                            .addElement(((JLabelExtended) component).getName())
                            .addAttribute("x", ((JLabelExtended) component).getX() + "")
                            .addAttribute("y", ((JLabelExtended) component).getY() + "")
                            .addAttribute("text", ((JLabelExtended) component).getText());
                } else {
                    Element item = root.addText("\n")
                            .addElement(((JLabelExtended) component).getName())
                            .addAttribute("x", ((JLabelExtended) component).getX() + "")
                            .addAttribute("y", ((JLabelExtended) component).getY() + "");
                }
            }
        }


        return document;
    }

    public void save(String path, JPanel jPanel, boolean writeAllText) {
        Document document = createDocument(jPanel, writeAllText);
        try {
            FileOutputStream os = new FileOutputStream(path);
            Writer out = new OutputStreamWriter(os, "UTF8");


            XMLWriter writer = new XMLWriter(out);
            writer.write(document);
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
